define(['bootstrapTable','layer','bootstrapFileinput','util','iCheck','fileInput'],function (bootstrapTable,layer,bootstrapFileinput,util,iCheck) {
    return{
        init:function () {
            $('input[type="checkbox"].flat-red, input[type="radio"].flat-red').iCheck({
                 checkboxClass: 'icheckbox_flat-green',
                 radioClass   : 'iradio_flat-green'
            });
            // alarmPkay()
            showData();
            /*添加布控人员*/
            $("#addFocusCrowd").click(function(){
                $("#id").val(0);
                $("#phoneNum").val("");
                $("#type").val("");
                $("#noticePeople").val("");
                $("#noticePhone").val("");
                $("#timeStart").val("");
                $("#timeEnd").val("");
                $("#days").val("");

                openLayer("布控人员信息",$("#myModal"))
                $(".sub").html("");
                $('input:radio[value=1],input:radio[value=2],input:radio[value=3]').iCheck('uncheck')
            });
            /*批量导入*/
            $("#batchImport").click(function(){
                initUpload();
            })
            /*关闭*/
            $(".btn_close").click(function(){
                $("#myModal").css({"display":"none"});
                layer.closeAll();
            });
            /*保存*/
            $("#btn_save").click(function(){
                var id =  $("#id").val();
                var data = {};
                // 进入区域告警
                var enterValue=new Array;
                var enterIds=new  Array;
                $("#enterAlarmSub span").each(function(){
                    enterValue.push($(this).text());
                    enterIds.push($(this).data("id"))
                });
                data.enterAlarmValue = enterValue;
                data.enterAlarmValueIds = enterIds;
                //离开区域告警
                var leaveValue=new Array;
                var leaveIds=new Array;
                $("#leaveAlarmSub span").each(function(){
                    leaveValue.push($(this).text());
                    leaveIds.push($(this).data("id"))
                });
                data.leaveAlarmValue = leaveValue;
                data.leaveAlarmValueIds = leaveIds;
                // console.log("离开区域告警值" + leaveValue);
                // console.log("离开区域告警ids" + leaveIds);
                var timeType = $('input:radio[name="timeType"]:checked').val();
                if(timeType == 1){ // 按天
                    data.timeType = 1;
                    data.days = $("#days").val();
                }else if(timeType == 2){ // 长期
                    data.timeType = 2;
                }else if(timeType == 3){ // 指定时间
                    data.timeType = 3;
                    data.timeStart = $("#timeStart").val();
                    data.timeEnd = $("#timeEnd").val();
                }
                data.phoneNum = $("#phoneNum").val();
                data.type = $("#type").val();
                data.noticePeople = $("#noticePeople").val();
                data.noticePhone = $("#noticePhone").val();
                if(id == 0){
                    $.ajax({// 添加
                        url:"/focusCrowdController/add",
                        dataType:"json",
                        type:"post",
                        data:data,
                        traditional: true, // 对象中含有数组
                        success:function(result){

                        }
                    })
                }else {
                    data.id = $("#id").val();
                    $.ajax({// 修改
                        url:"/focusCrowdController/update",
                        dataType:"json",
                        type:"post",
                        data:data,
                        traditional: true,
                        success:function(result){

                        }
                    })
                }

            });
            /*excel保存*/
            $("#excelSave").click(function(){
                var allTableData = $('#excelTable').bootstrapTable('getData');
                var list = new Array();
                var data = {}; // 定义一个对象
                for(var i = 0; i < allTableData.length; i++){
                    // console.log(allTableData[i]);
                    var fc = {};
                    fc.phoneNum = allTableData[i].phoneNum;
                    fc.noticePeople = allTableData[i].noticePeople;
                    fc.noticePhone = allTableData[i].noticePhone;
                    list.push(fc)
                }
                var setList = JSON.stringify(list);// 转为json格式字符串
                // 告警区域
                // 进入区域告警
                var enterValue=new Array;
                var enterIds=new  Array;
                $("#excelenterAlarmSub span").each(function(){
                    enterValue.push($(this).text());
                    enterIds.push($(this).data("id"))
                });
                data.enterAlarmValue = enterValue;
                data.enterAlarmValueIds = enterIds;
                //离开区域告警
                var leaveValue=new Array;
                var leaveIds=new Array;
                $("#excelleaveAlarmSub span").each(function(){
                    leaveValue.push($(this).text());
                    leaveIds.push($(this).data("id"))
                });
                data.leaveAlarmValue = leaveValue;
                data.leaveAlarmValueIds = leaveIds;
                // 布控时间
                var timeType = $('input:radio[name="exceltimeType"]:checked').val();
                if(timeType == 1){ // 按天
                    data.timeType = 1;
                    data.days = $("#exceldays").val();
                }else if(timeType == 2){ // 长期
                    data.timeType = 2;
                }else if(timeType == 3){ // 指定时间
                    data.timeType = 3;
                    data.timeStart = $("#exceltimeStart").val();
                    data.timeEnd = $("#exceltimeEnd").val();
                }
                data.type = $("#excelType").val();
                data.focusCrowdList = setList;
                $.ajax({// 添加
                    url:"/focusCrowdController/excelSave",
                    dataType:"json",
                    type:"post",
                    traditional: true, // 传到后台的数组去掉[]
                    data:data,
                    success:function(result){
                        if(result.code == 10001){
                            layer.closeAll();
                            layer.msg('保存成功！',{icon:1});
                            $('#bootstrapTable').bootstrapTable("refresh");
                        }
                    }
                })
            });
            /*检索*/
            $("#search").click(function(){
                $('#bootstrapTable').bootstrapTable("refresh");
            });
            /*进入区域告警*/
            $("#excelenterAlarm").click(function () {
                enterAlarmData(1)// excel
            });
            $("#enterAlarm").click(function () {
                enterAlarmData(2);
                $(this).blur();
            });

            /*离开区域告警*/
            $("#excelleaveAlarm").click(function () {
                leaveAlarmData(1)// excel
            });
            $("#leaveAlarm").click(function () {
                leaveAlarmData(2)
            })

        }
    };
    // 上传文件
    function initUpload() {
        $('#batchImport').blur();
        var indexL=layer.open({
            type: 1,
            title:"批量导入",
            anim: 2,
            closeBtn:1,
            zIndex:500,
            area:["60%","60%"],
            content:$("#inputFile"),
            end:function () {
                // location.reload();
            },
            cancel: function(index, layero){
                $("#inputFile").css({"display":"none"})
            }
        });
        var control = $('#excelFile');
        control.fileinput({
            language: 'zh', //设置语言
            uploadUrl: '/focusCrowdController/upload', //上传的地址
            uploadAsync: true, //默认异步上传
            showCaption: true,//是否显示标题
            showUpload: true, //是否显示上传按钮
            browseClass: "btn btn-primary", //按钮样式
            allowedFileExtensions: ["xlsx"], //接收的文件后缀
            maxFileCount: 1,//最大上传文件数限制
            previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
            showPreview: false, //是否显示预览
            previewFileIconSettings: {
                'docx': '<i class="fa fa-file-word-o text-primary"></i>',
                'xlsx': '<i class="fa fa-file-excel-o text-success"></i>',
                'xls': '<i class="fa fa-file-excel-o text-success"></i>',
                'pptx': '<i class="fa fa-file-powerpoint-o text-danger"></i>',
                'jpg': '<i class="fa fa-file-photo-o text-warning"></i>',
                'pdf': '<i class="fa fa-file-archive-o text-muted"></i>',
                'zip': '<i class="fa fa-file-archive-o text-muted"></i>',
            },
            uploadExtraData: function () {
                var extraValue = "test";
                return {"excelType": extraValue};
            }
        });
        control.on("fileuploaded", function (event, data, previewId, index) {
            // console.log(data);
            if(data.response.code == 10001)
            {
                //重置
                $("#excelFile").fileinput("clear");
                $("#excelFile").fileinput("reset");
                $('#excelFile').fileinput('refresh');
                $('#excelFile').fileinput('enable');
                layer.close(indexL);
                $("#inputFile").css({"display":"none"});
                openLayer("确认信息",$("#excelTableDiv"));
                var tableData = data.response.data;
                showExcelData(tableData)
            }
            else{

                //alert(data.files[index].name + "上传失败!" + data.response.message);
                //重置
                $("#excelFile").fileinput("clear");
                $("#excelFile").fileinput("reset");
                $('#excelFile').fileinput('refresh');
                $('#excelFile').fileinput('enable');
            }
        });
    }
    // 进入告警区域表格
    function enterAlarmData(flag) {
        var index_1 = layer.open({
            type: 1,
            title:"进入区域告警",
            anim: 2,
            closeBtn:1,
            area:["70%","80%"],
            content:$("#enterAlarmModel"),
            btn:['确定','取消'],
            yes:function(index, layero){
                var row = $('#enterAlarmTable').bootstrapTable('getSelections');
                var html="";
                for(var i = 0;i < row.length; i ++){
                    html+="<span data-id="+row[i].id+">"+row[i].name+"</span>"
                }
                if(flag === 1){
                    $("#excelenterAlarmSub").html(html);
                }else if (flag === 2) {
                    $("#enterAlarmSub").html(html);
                }
                $('#enterAlarmTable').bootstrapTable('refresh');
                layer.close(index_1);
            },
            btn2:function(index, layero){
                //layer.closeAll(index); //关闭当前窗口
                $('#enterAlarmTable').bootstrapTable('refresh');
            },
            cancel: function(index, layero){
                $("#enterAlarmModel").css({"display":"none"});
                $('#enterAlarmTable').bootstrapTable('refresh');
                layer.closeAll(index); //关闭当前窗口
            }
        });
        // 表格渲染
        showEnterAlarmData();
    }
    // 离开告警区域表格
    function leaveAlarmData(flag) {
        var index_1 = layer.open({
            type: 1,
            title:"离开区域告警",
            anim: 2,
            closeBtn:1,
            area:["70%","80%"],
            content:$("#leaveAlarmModel"),
            btn:['确定','取消'],
            yes:function(){
                var row = $('#leaveAlarmTable').bootstrapTable('getSelections');
                var html="";
                for(var i = 0;i < row.length; i ++){
                    html+="<span data-id="+row[i].id+">"+row[i].name+"</span>"
                }
                if(flag === 1){
                    $("#excelleaveAlarmSub").html(html);
                }else if (flag === 2) {
                    $("#leaveAlarmSub").html(html);
                }

                layer.close(index_1);

            },
            btn2:function(){
                layer.closeAll(index); //关闭当前窗口
            },
            cancel: function(index, layero){
                $("#leaveAlarmModel").css({"display":"none"})
            }
        });

        // 表格渲染
        showLeaveAlarmData();
    }
    function openLayer(title,$dom){
        $('#addFocusCrowd').blur();
        layer.open({
            type: 1,
            title:title,
            anim: 2,
            closeBtn:1,
            zIndex:500,
            area:["70%","80%"],
            content:$dom,
            end:function () {
                // location.reload();
            },
            cancel: function(index, layero){
                $dom.css({"display":"none"})
            }
        });
        util.datePicker($('[data-toggle="datepicker"]'),{format:'yyyy-MM-dd',autoHide:true,startDate:new Date()});
        util.setDate($("#timeStart"),'setDate',new Date());
    }
    //时间戳转换
    function fmtDate(obj,type){
        var date = new Date(obj);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
        Y = date.getFullYear() + '-';
        M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
        D = (date.getDate()< 10 ? '0'+(date.getDate()): date.getDate()) + ' ';
        h = (date.getHours()< 10 ? '0'+(date.getHours()): date.getHours()) + ':';
        m = (date.getMinutes()< 10 ? '0'+(date.getMinutes()): date.getMinutes()) + ':';
        s = (date.getSeconds()< 10 ? '0'+(date.getSeconds()): date.getSeconds());
        if(obj == null){
            return null
        }else if(type=='date'){
            return Y+M+D;
        }else{
            return Y+M+D+h+m+s;
        }
    }
    function showData(){
        window.openEvent={
            'click .editor':function (e,value,row,index) {
                $.ajax({
                    url:"/focusCrowdController/findById",
                    dataType:"json",
                    type:"post",
                    data:{
                        "id":row.id
                    },
                    success:function(result){
                        if(result.code == 10001){
                            var data = result.data;
                            openLayer("修改用户信息",$("#myModal"));
                            $("#id").val(row.id);
                            $("#phoneNum").val(row.phoneNum);
                            $("#type").val(row.type);
                            $("#noticePeople").val(row.noticePeople);
                            $("#noticePhone").val(row.noticePhone);
                            // 布控时间
                            if(data.timeType == 1){ // 按天
                                $("input:radio[value=1]").iCheck('check')
                                $("#days").val(data.days+1);
                            }else if(data.timeType == 2){ // 长期
                                $("input:radio[value=2]").iCheck('check')
                            }else if(data.timeType == 3){ // 指定时间
                                $("input:radio[value=3]").iCheck('check')
                                $("#timeStart").val(fmtDate(row.timeStart).substring(0,10),'date');
                                $("#timeEnd").val(fmtDate(row.timeEnd).substring(0,10),'date');
                            }
                            // 告警类型
                            var html1="";
                            for(var j = 0;j < data.enterAlarmValue.length; j ++){
                                html1+="<span data-id="+data.enterAlarmValueIds[j]+">"+data.enterAlarmValue[j]+"</span>"
                            }
                            $("#enterAlarmSub").html(html1);
                            var html2="";
                            for(var k = 0;k < data.leaveAlarmValue.length; k ++){
                                html2+="<span data-id="+data.leaveAlarmValueIds[k]+">"+data.leaveAlarmValue[k]+"</span>"
                            }
                            $("#leaveAlarmSub").html(html2);
                        }
                    }
                });
            },
            'click .delete':function (e,value,row,index) {
                layer.confirm('您确定要删除此用户？', {title:'删除用户信息',icon: 2,
                    btn: ['确定','取消'] //按钮
                }, function(){
                    $.ajax({
                        url:"/focusCrowdController/delByIds",
                        dataType:"json",
                        type:"post",
                        data:{
                            "id":row.id
                        },
                        success:function(result){
                            $("#myModal").css({"display":"none"});
                            layer.closeAll();
                            $('#bootstrapTable').bootstrapTable("refresh");
                        }
                    });
                });
            }
        };
        $('#bootstrapTable').bootstrapTable({
            url: "/focusCrowdController/pageSelect", // 获取表格数据的url
            method:'post',
            cache: false,       // 设置为 false 禁用 AJAX 数据缓存， 默认为true
            striped: true,      //表格显示条纹，默认为false
            pagination: true,   // 在表格底部显示分页组件，默认false
            contentType:'application/x-www-form-urlencoded',
            sidePagination: 'server', // 设置为服务器端分页，必要
            queryParamsType : "",
            queryParams:function(params){
                return tem={
                    rows:params.pageSize,
                    page:params.pageNumber,
                    code:$("#code").val()
                }
            },
            clickToSelect:false,
            columns: [
                {
                    title: '序号',
                    align: 'center',
                    formatter:showNumber,
                    width:'1%'
                },
                // {
                //     field: 'ck',
                //     checkbox: true,
                //     align: 'center',
                //     valign: 'middle'
                // },
                {
                    field: 'code',
                    title: '人员编号',
                    align: 'center',
                    valign: 'middle',
                    width:'15%'

                }, {
                    field: 'phoneNum',
                    title: '手机号',
                    align: 'center',
                    valign: 'middle',
                    width:'10%',
                    formatter:function (value, row, index) {
                        var reg = /(\d{3})(\d{4})(\d{4})/;
                        return value.replace(reg,'$1****$3');
                    }
                }, {
                    field: 'type',
                    title: "类型",
                    align: 'center',
                    valign: 'middle',
                    width:'10%'
                },{
                    field:'noticePeople',
                    title:'通知人',
                    align:'center',
                    valign:'middle',
                    width:'10%'
                },{
                    field:'noticePhone',
                    title:'通知人手机号',
                    align:'center',
                    valign:'middle',
                    width:'10%',
                    formatter:function (value, row, index) {
                        var reg = /(\d{3})(\d{4})(\d{4})/;
                        return value.replace(reg,'$1****$3');
                    }
                },{
                    field:'createTime',
                    title:'导入时间',
                    align:'center',
                    valign:'middle',
                    width:'15%',
                    formatter: function(value, row, index){
                        return fmtDate(value,'time')
                    }
                },{
                    field:'timeStart',
                    title:'监控开始时间',
                    align:'center',
                    valign:'middle',
                    width:'10%',
                    formatter: function(value, row, index){
                        return fmtDate(value,'date')
                    }
                },{
                    field:'timeEnd',
                    title:'监控结束时间',
                    align:'center',
                    valign:'middle',
                    width:'10%',
                    formatter: function(value, row, index){
                        return fmtDate(value,'date');
                    }
                }
                , {
                    field:'operator',
                    title: "操作",
                    align: 'center',
                    valign: 'middle',
                    width:'10%',
                    events:openEvent,
                    formatter: function(value, row, index){
                        return ['<button class="btn btn-xs btn-info btn-operator-gew editor"><i class="fa fa-edit"></i></button>','<button class="btn btn-xs btn-danger delete"><i class="fa fa-trash-o"></i></button>'].join("");
                    }
                }
            ],
            onLoadSuccess: function(data){  //加载成功时执行

            },
            onLoadError: function(){  //加载失败时执行
                //console.info("加载数据失败");
            }
        });
    }
    function showExcelData(tableData) {
        window.openEvent={
            //删除行
            'click #excelDelete':function (e,value,row,index) {
                var $table = $('#excelTable');
                var pageNumber=$table.bootstrapTable('getOptions').pageNumber;
                var pageSize=$table.bootstrapTable('getOptions').pageSize;
                //起始位置以及长度
                tableData.splice((pageNumber-1)*pageSize+index,1)
                $table.bootstrapTable('load',tableData);
            }
        };
        $('#excelTable').bootstrapTable({
            data:tableData,
            cache: false,       // 设置为 false 禁用 AJAX 数据缓存， 默认为true
            striped: true,      //表格显示条纹，默认为false
            pagination: true,   // 在表格底部显示分页组件，默认false
            sidePagination: 'client', // 设置为服务器端分页，必要
            clickToSelect:false,
            columns: [
                {
                    field: 'number',
                    title: '序号',
                    align: 'center',
                    formatter:showNumber,
                    width:'1%'
                },
                 {
                    field: 'phoneNum',
                    title: '手机号',
                    align: 'center',
                    valign: 'middle',
                    width:'30%'
                },{
                    field:'noticePeople',
                    title:'通知人',
                    align:'center',
                    valign:'middle',
                    width:'30%'
                },{
                    field:'noticePhone',
                    title:'通知人手机号',
                    align:'center',
                    valign:'middle',
                    width:'30%'
                }
                , {
                    field:'operator',
                    title: "操作",
                    align: 'center',
                    valign: 'middle',
                    width:'10%',
                    events:openEvent,
                    formatter: function(value, row, index){
                        return ['<button class="btn btn-xs btn-danger" id="excelDelete"><i class="fa fa-trash-o"></i></button>'].join("");
                    }
                }
            ],
            onLoadSuccess: function(data){  //加载成功时执行

            },
            onLoadError: function(){  //加载失败时执行
                //console.info("加载数据失败");
            }
        });
    }

    // 进入告警区域表格
    function showEnterAlarmData() {
        $('#enterAlarmTable').bootstrapTable({
            url: "/alarmEnterAreaController/pageSelect", // 获取表格数据的url
            method:'post',
            cache: false,       // 设置为 false 禁用 AJAX 数据缓存， 默认为true
            striped: true,      //表格显示条纹，默认为false
            pagination: true,   // 在表格底部显示分页组件，默认false
            contentType:'application/x-www-form-urlencoded',
            sidePagination: 'server', // 设置为服务器端分页，必要
            queryParamsType : "",
            pageSize : 9999,
            queryParams:function(params){
                return tem={
                    rows:params.pageSize,
                    page:params.pageNumber
                }
            },
            clickToSelect:false,
            columns: [
                {
                    title: '序号',
                    align: 'center',
                    formatter:showNumber,
                    width:'1%'
                },{
                    field: 'ck',
                    checkbox: true,
                    align: 'center',
                    valign: 'middle'
                },
                {
                    field: 'name',
                    title: '编号',
                    align: 'center',
                    valign: 'middle',
                    width:'100%'
                }
            ],
            onLoadSuccess: function(data){  //加载成功时执行

            },
            onLoadError: function(){  //加载失败时执行
                //console.info("加载数据失败");
            }
        });
    }
    // 离开告警区域表格
    function showLeaveAlarmData() {
        $('#leaveAlarmTable').bootstrapTable({
            url: "/positionAreaController/pageSelect", // 获取表格数据的url
            method:'post',
            cache: false,       // 设置为 false 禁用 AJAX 数据缓存， 默认为true
            striped: true,      //表格显示条纹，默认为false
            pagination: true,   // 在表格底部显示分页组件，默认false
            contentType:'application/x-www-form-urlencoded',
            sidePagination: 'server', // 设置为服务器端分页，必要
            queryParamsType : "",
            pageSize : 9999,
            queryParams:function(params){
                return tem={
                    rows:params.pageSize,
                    page:params.pageNumber
                }
            },
            clickToSelect:false,
            columns: [
                {
                    title: '序号',
                    align: 'center',
                    formatter:showNumber,
                    width:'1%'
                },{
                    field: 'ck',
                    checkbox: true,
                    align: 'center',
                    valign: 'middle'
                },
                {
                    field: 'name',
                    title: '编号',
                    align: 'center',
                    valign: 'middle',
                    width:'100%'
                }
            ],
            onLoadSuccess: function(data){  //加载成功时执行

            },
            onLoadError: function(){  //加载失败时执行
                //console.info("加载数据失败");
            }
        });
    }

    function showNumber(value, row, index){
        var options = $('#bootstrapTable').bootstrapTable('getOptions');
        return options.pageSize*(options.pageNumber-1)+index + 1;
    };
    function alarmPkay(){
        $(".checkInput").on('ifClicked', function (event) {
            if ($(this).attr("checked",true)) {
                $(this).parent().parent().next().slideToggle("slow");
                $("#"+$(this).parent().parent().next().attr("id")+" input").iCheck('check');
            } else {

            };

        });
    }
})